<template> 
    <span>
       
    </span>
</template>

<script setup> 
let appInfo={};
if(window.electronAPI){
  getAppInfo();
}
async function getAppInfo(){
  appInfo= await window.electronAPI.getAppInfo() 
}
import { getCurrentInstance,ref, defineProps,onMounted,onUnmounted } from 'vue';
import { useUserStore } from '../stores/user'
import { useLicenseStore } from '../stores/license'
import { useThemeStore } from '../stores/theme'
import WebSocketReconnect from '../utils/websocketTool'
import CryptoJS from 'crypto-js';
import Base64 from 'crypto-js/enc-base64'
const app = getCurrentInstance()
const userStore = useUserStore()
const licenseStore = useLicenseStore()
const themeStore = useThemeStore()
const props = defineProps({
  onClick: Function,
  url:String,
  clientId:String,
  orgId:String,
});
// const licenseInfo=ref(null);
let websocket = null
let wsClientHost = null
let lastThemeUrl = "";
onMounted(() => {  
  console.log("wsClient init")  
  let url=props.url
  console.log(props.url)  
  lastThemeUrl=themeStore.lastUrl;
  wsClientHost=props.url
  initWs(wsClientHost);
});
onUnmounted(() => {
   websocket.close()
});

function reJoin(a){
  websocket=a;
  let msg={"event":"/client/join","data":{"clientId":"","orgId":""}};
      msg.data.clientId=props.clientId;
      msg.data.orgId=userStore.orgId; 
  websocket.sendMessage(JSON.stringify(msg));
  //接收到消息的回调方法
  websocket.socket.onmessage = function (msg) { 
    const { data, event } = JSON.parse(msg.data);
    console.log("msg:"+event);
    switch (event) {
      case 'showData':
        if(data&&data.url){
          setTimeout(function(){
              app?.proxy?.$Bus.emit('ShowThemeWebURL', {url:data.url})
          },2000) 
        }
        break; 
      case 'init':
        if(lastThemeUrl){
          setTimeout(function(){
              app?.proxy?.$Bus.emit('ShowThemeWebURL', {url:lastThemeUrl})
          },2000) 
        }
        break; 
      case 'restart':
        window.electronAPI.reloadApp({}); 
        break; 
      case 'reload':
        window.electronAPI.reloadWin({}); 
        break; 
      default: 
        break;
    }
  }
}
function initWs(url){
  if(!url){
    return;
  }
  console.log("wsClient init") 
  //判断当前浏览器是否支持WebSocket
  if ('WebSocket' in window) {
    //连接WebSocket节点
    websocket = new WebSocketReconnect(url,function(a){
      reJoin(a)
    })
  } else {
    console.log('浏览器不支持webSocket')
  }    
  //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
  window.onbeforeunload = function () {
    websocket.close()
  }
  //关闭连接
  function closeWebSocket() {
    websocket.close()
  } 
}
</script>

<style scoped> 
</style>